package com.vitabuybuy.tv.ui.mine.coupons.viewmodel

import android.view.View
import androidx.databinding.ObservableArrayList
import com.library.common.base.BaseViewModel
import com.library.common.base.MessageModel
import com.library.common.ext.rxHttpRequest
import com.library.common.net.error.msg
import com.library.common.net.loadingtype.LoadingType
import com.library.common.toast.XToast
import com.vitabuybuy.tv.BR
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.dto.MyCouponDto
import com.vitabuybuy.tv.inter.OnItemCouponsListener
import com.vitabuybuy.tv.network.CouponCenterRepository
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind

class MyCouponsViewModel : BaseViewModel() {
    private val itemOnClickListener = object : OnItemCouponsListener {
        override fun onItemClick(item: MyCouponDto, position: Int) {
            defUI.msgEvent.postValue(MessageModel(2, obj = item))
        }
    }
    val couponlist = ObservableArrayList<MyCouponDto>()

    //网格布局的adapter绑定
    val couponBinding: OnItemBind<MyCouponDto> =
        OnItemBind { itemBinding: ItemBinding<Any>, position: Int, item: MyCouponDto ->
            itemBinding.set(BR.itemBean, R.layout.item_coupon).bindExtra(BR.position, position)
                .bindExtra(BR.listenner, itemOnClickListener)
        }

    fun getCouponList(pageNumber: Int, status: String) {
        val map = HashMap<String, Any>()
        if (status.isNotEmpty()) map["userCouponRecord"] = mapOf(Pair("status", status))
        rxHttpRequest {
            onRequest = {
                val it = CouponCenterRepository.getMyCouponsList(map, pageNumber).await()
                if (pageNumber == 1) {
                    couponlist.clear()
                }
                couponlist.addAll(it)
                if (couponlist.isEmpty()) {
                    statusView.set(LoadingType.SHOW_EMPTY)
                }else{
                    statusView.set(LoadingType.SHOW_CONTENT)
                }
                defUI.msgEvent.postValue(MessageModel(1, arg1 = it.size))
            }
            onError = {
                XToast.normal(it.msg)
            }
            isLoadingType = true
            isRefresh = pageNumber == 1
        }
    }
}
